package com.itheima.config;

import com.itheima.common.CustomException;
import com.itheima.controller.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 自定义全局异常处理器
 * @Auther: 宋H
 * @Date: 2022/9/5
 * @Description: com.itheima.config
 * @version: 1.0
 */
@Slf4j
@RestControllerAdvice(annotations={RestController.class})
public class ProjectException {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String>  exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        if(ex.getMessage().contains("Duplicate entry")){
            String[] str = ex.getMessage().split(" ");
            return R.error(str[2]+"用户已存在");
        }
        return R.error("一个未知的错误,稍后重试");
    }

    @ExceptionHandler(CustomException.class)
    public R<String>  exceptionHandler(CustomException ex){
        log.error(ex.getMessage());

        return R.error(ex.getMessage());
    }
//    @ExceptionHandler(DishException.class)
//    public R<String>  exceptionHandler(DishException ex){
//        log.error(ex.getMessage());
//
//        return R.error(ex.getMessage());
//    }
}
